热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

在Matplotlib中将图例作为单独的图片获取-GetlegendasaseparatepictureinMatplotlib

ImdevelopingaWebapplicationandwanttodisplayafigureanditslegendindifferentlocations

I'm developing a Web application and want to display a figure and its legend in different locations on the page. Which means I need to save the legend as a separate png file. Is this possible in Matplotlib in a more or less straightforward way?

我正在开发一个Web应用程序,并希望在页面上的不同位置显示一个图形及其图例。这意味着我需要将图例保存为单独的png文件。这在Matplotlib中是否可能以一种或多或少的直接方式实现?

5 个解决方案

#1


18  

This could work:

这可能有效:

import pylab
fig = pylab.figure()
figlegend = pylab.figure(figsize=(3,2))
ax = fig.add_subplot(111)
lines = ax.plot(range(10), pylab.randn(10), range(10), pylab.randn(10))
figlegend.legend(lines, ('one', 'two'), 'center')
fig.show()
figlegend.show()
figlegend.savefig('legend.png')

It can be tricky though to get the size of the legend figure right in an automated manner.

虽然以自动方式获得图例图形的大小,但这可能很棘手。

#3


6  

This calculates the size of the legend automatically. If mode == 1, the code is similar to Steve Tjoa's answer, while mode == 2 is similar Andre Holzner's answer.

这会自动计算图例的大小。如果mode == 1,代码类似于Steve Tjoa的答案,而mode == 2则类似于Andre Holzner的答案。

The loc parameter must be set to 'center' to make it work (but I do not know why this is necessary).

loc参数必须设置为'center'才能使其工作(但我不知道为什么这是必要的)。

mode = 1
#mode = 2

import pylab
fig = pylab.figure()
if mode == 1:
    lines = fig.gca().plot(range(10), pylab.randn(10), range(10), pylab.randn(10))
    legend_fig = pylab.figure(figsize=(3,2))
    legend = legend_fig.legend(lines, ('one', 'two'), 'center')
if mode == 2:
    fig.gca().plot(range(10), pylab.randn(10), range(10), pylab.randn(10), label='asd')
    legend_fig = pylab.figure()
    legend = pylab.figlegend(*fig.gca().get_legend_handles_labels(), loc = 'center')
legend.get_frame().set_color('0.70')
legend_fig.canvas.draw()
legend_fig.savefig('legend_cropped.png',
    bbox_inches=legend.get_window_extent().transformed(legend_fig.dpi_scale_trans.inverted()))
legend_fig.savefig('legend_original.png')

Original (uncropped) legend:

原始(未剪切)传奇:

如果由于某种原因您只想隐藏轴标签,您可以使用:

ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)

or if, for some weirder reason, you want to hide the axes frame but not the axes labels you can use:

或者,如果出于某种奇怪的原因,您想要隐藏轴框架而不是轴标签,您可以使用:

ax.set_frame_on(False)

ps: this answer has been adapted from my answer to a duplicate question

ps:这个答案改编自我对一个重复问题的回答


推荐阅读
author-avatar
518094haha
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有